package com.sunseagear.common.base.http;

import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.sunseagear.common.base.serialize.CustomLongSerializer;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.List;

/**
 * 表格分页数据对象
 *
 */
@Data
@NoArgsConstructor
public class RPage<T> implements Serializable {

    public static final int DEFAULT_SUCCESS_CODE = HttpStatus.HTTP_OK;
    public static final int DEFAULT_FAIL_CODE = HttpStatus.HTTP_INTERNAL_ERROR;

    public static final String DEFAULT_SUCCESS_MSG = "操作成功";
    public static final String DEFAULT_FAIL_MSG = "操作失败";


    /**
     * 总记录数
     */
    @JsonSerialize(using = CustomLongSerializer.class)
    private long total;

    /**
     * 每页数量
     */
    @JsonSerialize(using = CustomLongSerializer.class)
    private long size;

    /**
     * 页数
     */
    @JsonSerialize(using = CustomLongSerializer.class)
    private long pages;

    /**
     * 当前页数
     */
    @JsonSerialize(using = CustomLongSerializer.class)
    private long current;

    /**
     * 返回值，是否成功
     */
    private boolean success;
    /**
     * 列表数据
     */
    private List<T> data;

    /**
     * 消息状态码
     */
    private int code;

    /**
     * 消息内容
     */
    private String msg;


    public static <T> RPage<T> success(IPage<T> data) {
        return restResult(DEFAULT_SUCCESS_CODE, DEFAULT_SUCCESS_MSG, data);
    }

    public static <T> RPage<T> success(String msg, IPage<T> data) {
        return restResult(DEFAULT_SUCCESS_CODE, msg, data);
    }


    public static <T> RPage<T> fail(IPage<T> data) {
        return restResult(DEFAULT_FAIL_CODE, DEFAULT_FAIL_MSG, data);
    }

    public static <T> RPage<T> fail(String msg, IPage<T> data) {
        return restResult(DEFAULT_FAIL_CODE, msg, data);
    }

    private static <T> RPage<T> restResult(int code, String msg, IPage<T> data) {
        return restResult(R.DEFAULT_SUCCESS_CODE == code, data, code, msg);
    }

    private static <T> RPage<T> restResult(boolean success, IPage<T> data, int code, String msg) {
        RPage<T> r = new RPage<>();
        r.setTotal(data.getTotal());
        r.setSize(data.getSize());
        r.setPages(data.getPages());
        r.setCurrent(data.getCurrent());
        r.setSuccess(success);
        r.setCode(code);
        r.setData(data.getRecords());
        r.setMsg(msg);
        return r;
    }
}
